import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from utils.config_utils import config
from utils.logger_utils import logger
import os


class EmailUtils:
    def __init__(self):
        self.smtp_server = config.get_value('email', 'smtp_server')
        self.smtp_port = config.get_int('email', 'smtp_port')
        self.sender = config.get_value('email', 'sender')
        self.password = config.get_value('email', 'password')
        self.receivers = config.get_value('email', 'receivers').split(',')

    def send_email(self, subject, content, report_file=None):
        try:
            # 创建一个带附件的邮件实例
            message = MIMEMultipart()
            message['From'] = self.sender
            message['To'] = ','.join(self.receivers)
            message['Subject'] = subject

            # 添加邮件正文
            message.attach(MIMEText(content, 'html', 'utf-8'))

            # 添加附件
            if report_file and os.path.exists(report_file):
                with open(report_file, 'rb') as f:
                    attachment = MIMEApplication(f.read(), _subtype='html')
                    attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(report_file))
                    message.attach(attachment)
                logger.info(f"添加附件: {report_file}")

            # 发送邮件
            with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port) as server:
                server.login(self.sender, self.password)
                server.sendmail(self.sender, self.receivers, message.as_string())

            logger.info("邮件发送成功")
        except Exception as e:
            logger.error(f"邮件发送失败: {e}")
            raise


email_utils = EmailUtils()
